package cmd

import (
	"context"
	_ "mldong/internal/modules/sys/controller" // 确保所有sys控制器包被导入
	"mldong/utility"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"mldong/api/base"
	"mldong/internal/middleware"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			// 初始化配置
			// 通常在main.go中初始化
			errInit := utility.InstanceConstantContext().InitConstantContext(ctx)
			if errInit != nil {
				// 处理初始化错误
				panic(errInit)
			}
			s := g.Server()
			// 统一错误处理
			s.BindStatusHandler(404, func(r *ghttp.Request) {
				r.Response.Status = http.StatusOK
				r.Response.WriteJson(base.Fail(99990404, "接口不存在此功能正在建设中，敬请期待！"))
			})
			s.BindStatusHandler(500, func(r *ghttp.Request) {
				// 1. 清空框架的默认错误输出
				r.Response.ClearBuffer()
				// 2. 修改状态码
				r.Response.Status = http.StatusOK
				// 3. 自定义错误输出
				r.Response.WriteJson(base.Fail(99990500, "服务器内部错误"))
			})
			s.Group("/", func(group *ghttp.RouterGroup) {
				// 注册中间件
				group.Middleware(middleware.GetMiddlewares()...)
				// group.Bind(
				// 	controller.NewUserController(),
				// 	controller.NewRoleController(),
				// 	controller.NewAuthController(),
				// 	controller.NewPostController(),
				// )
				// 注册控制器
				group.Bind(utility.GetControllers()...)
			})
			s.Run()
			return nil
		},
	}
)
